"use strict";
const electron = require("electron");
const { screen } = require('electron');
const { app, BrowserWindow, ipcMain } = require("electron");
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib';
let frontWindow, frontBaseUrl, frontParams;
const isDevelopment = process.env.NODE_ENV !== "production";

function createFrontWindow() {
  const { width, height } = electron.screen.getPrimaryDisplay().bounds;
  console.log("Creating front window", width, height);
  frontWindow = new BrowserWindow({
    width,
    height,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: false,
      enableRemoteModule: true,
      webSecurity: true,  // 开启Web安全策略
      backgroundThrottling: false,  // 避免后台窗口被降频
    },
    resizable: true,
    transparent: false,
    fullscreen: false,
    frame: true,
  });

  frontWindow.loadURL(`${frontBaseUrl}?${frontParams}`);

  frontWindow.on("closed", () => {
    frontWindow = null;
  });

  frontWindow.setMenuBarVisibility(false);

  frontWindow.maximize();

  frontWindow.on("maximize", () => {
  });

  frontWindow.on("unmaximize", () => {
    const newWidth = 1600;
    const newHeight = 800;

    const x = Math.round((width - newWidth) / 2);
    const y = Math.round((height - newHeight) / 2);

    frontWindow.setBounds({ width: newWidth, height: newHeight, x, y });
  });
}

ipcMain.on('broadcast-window-close', () => {
  if (frontWindow) {
    frontWindow.close();
  }
});

function listenFrontWindowEvents() {
  ipcMain.on('open-front-window', (event, args) => {
    const { currentUrl, loginUrl } = args;
    if (!frontWindow) {
      frontBaseUrl = currentUrl;
      frontParams = loginUrl;
      createFrontWindow();
    } else {
      if (frontWindow.isMinimized()) {
        frontWindow.restore();
      }
      frontWindow.focus();
    }
  });
}

export { listenFrontWindowEvents };